package top.lingkang.sprite;

import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Pool;
import top.lingkang.constants.BulletType;
import top.lingkang.screen.PlayScreen;

/**
 * @author lingkang
 * @date 2021/10/16 19:25
 * @description
 */
public class BulletSprite extends BaseSprite implements Pool.Poolable {
    public BulletType type;
    public float moveSpeed;
    public boolean alive;
    private PlayScreen playScreen;

    public void init(BulletType type, float moveSpeed, float x, float y, PlayScreen playScreen) {
        alive = true;
        this.type = type;
        this.moveSpeed = moveSpeed;
        this.playScreen = playScreen;
        setPosition(x, y);
        switch (type) {
            case PLAYER: {
                // 子弹
                setRegion(playScreen.game.assetManager.get("tiles/t-0.png", Texture.class));
                setRegionWidth(16);
                setRegionHeight(16);
                break;
            }
            case ENEMY: {
                setRegion(playScreen.game.assetManager.get("tiles/t-9.png", Texture.class));
                setRegionWidth(16);
                setRegionHeight(16);
                break;
            }
        }
    }

    public void update(SpriteBatch batch) {
        if (getY() > 670 || getY() < -48 || getX() > 512 || getX() < -48) {
            alive = false;
            return;
        }

        if (type == BulletType.PLAYER) {
            // 玩家子弹移动方向
            setY(getY() + moveSpeed);
            // 判断是否打中敌人
            int size = playScreen.enemyPlane.size;
            for (int i = size; --i >= 0; ) {
                EnemyPlaneSprite sprite = playScreen.enemyPlane.get(i);
                if (this.hasOverlap(sprite)) {
                    sprite.beHit();// 中弹
                    alive = false;// 回收子弹
                    return;
                }
            }
        } else {
            // 敌人子弹
            setY(getY() - moveSpeed);
            if (this.hasOverlap(playScreen.playerPlane)) {
                playScreen.playerPlane.beHit();
                // 击中玩家
                alive = false;
                return;
            }
        }
        // 绘制子弹
        batch.draw(this, getX(), getY());
    }

    @Override
    public void reset() {

    }

}
